package cn.wolfcode.wolf2w.service.imp;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.domain.TravelComment;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
//import cn.wolfcode.wolf2w.query.TravelCondition;
import cn.wolfcode.wolf2w.query.TravelCondition;
import cn.wolfcode.wolf2w.query.TravelQuery;
import cn.wolfcode.wolf2w.repository.TravelRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.xml.transform.Templates;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
//@Transactional  暂时先别管事务
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelRepository repository;

    @Autowired
    private IDestinationService destinationService;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private IUserInfoService userInfoService;

    @Override
    public Travel get(String id) {

        //查询当前游记的时候顺便将其中的属性 作者 也查询出来填充进去,
        //否则游记明细页面用户的头像和昵称等内容显示错误,会报错
        Travel travel = repository.findById(id).orElse(null);
        if (travel != null) {
            UserInfo userInfo = userInfoService.get(travel.getUserId());
            travel.setAuthor(userInfo);


            travel.setDest(destinationService.get(travel.getDestId()));
        }

        return travel;

    }

    @Override
    //page对象里面包括: 总页数 每页显示条数......
    public Page<Travel> query(TravelQuery qo) {
        Query query = new Query();
        if (StringUtils.hasLength(qo.getDestId())) {
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
//出行时间
        TravelCondition day = qo.getDay();
        if (day != null) {
            query.addCriteria(Criteria.where("day").gte(day.getMin()).lte(day.getMax()));
        }

        TravelCondition ex = qo.getPerExpend();
        if (ex != null) {
            query.addCriteria(Criteria.where("perExpend").gte(ex.getMin()).lte(ex.getMax()));
        }
        Pageable pageable = null;


        if (qo.getOrderType() == 1) {
            pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "createTime");
        } else if (qo.getOrderType() == 2) {
            pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "viewnum");
        } else {
            pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "_id");
        }

        Page<Travel> page = DBHelper.query(template, Travel.class, query, pageable);
        for (Travel travel : page) {
            travel.setAuthor(userInfoService.get(travel.getUserId()));
        }

        return page;
    }

    @Override
    public String saveOrUpdate(Travel travel) {

        //添加或更新时, 需要准备的内容

        //1: 目的地名称
        Destination dest = destinationService.get(travel.getDestId());
        travel.setDestName(dest.getName());

        //3:创建时间/最后更新时间
        travel.setLastUpdateTime(new Date());
        if (!StringUtils.hasLength(travel.getId())) {
            //添加
            travel.setId(null);
            //创建时间
            travel.setCreateTime(new Date());

            repository.save(travel);
        } else {
            //更新
            //方案1: 1:查询  2: 替代  3:save
            //方案2: 显示使用update逻辑 update set...
            //条件
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(travel.getId()));

            DBHelper.update(template, query, travel,
                    "destId", "destName", "title",
                    "coverUrl", "travelTime", "perExpend",
                    "day", "person", "lastUpdateTime",
                    "isPublic", "state", "summary", "content");
        }

        return travel.getId();
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }


    @Override
    public List<Travel> getViewnumTop3(String destId) {
        //点击量前3
        Pageable of = PageRequest.of(0, 3, Sort.Direction.DESC, "viewnum");
        return repository.findByDestId(destId, of);
    }

    @Override
    public List<Travel> list() {
        return repository.findAll();
    }

    @Override
    public List<Travel> findByDestName(String destName) {
        List<Travel> list = repository.findByDestName(destName);
        for (Travel travel : list) {
            //用户信息
            travel.setAuthor(userInfoService.get(travel.getUserId()));
        }
        return list;
    }

    @Override
    public void update(Travel travel) {
        repository.save(travel);
    }

    @Override
    public void audit(String id, int state) {
        Travel travel = this.get(id);
        if (travel == null) {
            throw new LogicException("参数异常");
        }
        if (travel.getState() != Travel.STATE_WAITING) {
            throw new LogicException("游记不是待审核状态，不允许审核");
        }
        if (state == Travel.STATE_RELEASE) {
            travel.setState(state);
            travel.setLastUpdateTime(new Date());
            travel.setReleaseTime(new Date());
            this.update(travel);

        } else if (state == Travel.STATE_REJECT) {
            travel.setState(state);
            travel.setLastUpdateTime(new Date());
            travel.setReleaseTime(null);
            this.update(travel);
        } else {
            throw new LogicException("状态不对");
        }
    }
}
